#include "steering_gear.h"

void steering_gear_gpio_init()
{
    // 推挽输出	P21
    P2_MODE_OUT_PP(GPIO_Pin_1);
}

void steering_gear_config()
{
    PWMx_InitDefine PWMx_InitStructure;

    // 配置PWM6
    PWMx_InitStructure.PWM_Mode      = CCMRn_PWM_MODE1; // 模式,		CCMRn_FREEZE,CCMRn_MATCH_VALID,CCMRn_MATCH_INVALID,CCMRn_ROLLOVER,CCMRn_FORCE_INVALID,CCMRn_FORCE_VALID,CCMRn_PWM_MODE1,CCMRn_PWM_MODE2
    PWMx_InitStructure.PWM_Duty      = 0;               // PWM占空比时间, 0~Period
    PWMx_InitStructure.PWM_EnoSelect = ENO6P;           // 输出通道选择,	ENO1P,ENO1N,ENO2P,ENO2N,ENO3P,ENO3N,ENO4P,ENO4N / ENO5P,ENO6P,ENO7P,ENO8P
    PWM_Configuration(PWM6, &PWMx_InitStructure);       // 初始化PWM,  PWMA,PWMB

    // 配置PWMB
    PWMx_InitStructure.PWM_Period        = STEER_PERIOD - 1; // 周期时间,   0~65535
    PWMx_InitStructure.PWM_DeadTime      = 0;                // 死区发生器设置, 0~255
    PWMx_InitStructure.PWM_MainOutEnable = ENABLE;           // 主输出使能, ENABLE,DISABLE
    PWMx_InitStructure.PWM_CEN_Enable    = ENABLE;           // 使能计数器, ENABLE,DISABLE
    PWM_Configuration(PWMB, &PWMx_InitStructure);            // 初始化PWM通用寄存器,  PWMA,PWMB

    // 切换PWM通道
    PWM6_SW(PWM6_SW_P21); // PWM6_SW_P21,PWM6_SW_P54,PWM6_SW_P01,PWM6_SW_P75

    // 初始化PWMB的中断
    NVIC_PWM_Init(PWMB, DISABLE, Priority_0);

    // 10分频, STCH_PWM.h  515行
    PWMB_Prescaler(PRE - 1);
}

void steering_gear_init()
{
    steering_gear_gpio_init();
    steering_gear_config();
}

void set_angle_value(float angle)
{
    PWMx_Duty duty; // duty是结构体变量
    float value = 500 + (angle * 2000 / 180.0);
    // printf("value = %.1f\n", value);
    // 算出占空比  (value / 20000) * PERIOD
    // 给占空比的结构体成员赋值
    duty.PWM6_Duty = (value / 20000) * PERIOD;
    // 设置占空比
    UpdatePwm(PWMB, &duty);
}
